package com.eaero.service.email;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.mail.MailAccount;
import cn.hutool.extra.mail.MailUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.eaero.CommonResp;
import com.eaero.entity.TraceUser;
import com.eaero.service.ITraceUserService;
import com.eaero.vo.SendEmailRequest;
import com.google.common.util.concurrent.RateLimiter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;

/**
 * @author zzj
 * @date 2023/3/20 9:38
 * @description
 */
@Service
public class EmailServiceImpl implements EmailService {

    @Autowired
    private ITraceUserService userService;

    @Autowired
    private MailAccount mailAccount;

    /**
     * 测试邮件设置限流，一秒钟处理2个
     */
    private static RateLimiter rateLimiter = RateLimiter.create(10);

    @Override
    public CommonResp sendEmail(SendEmailRequest request) {
        String userCode = request.getUserCode();
        TraceUser user = userService.getOne(Wrappers.<TraceUser>lambdaQuery()
                .eq(TraceUser::getUserCode, userCode));

        if (ObjectUtil.isEmpty(user)) {
            return CommonResp.buildSuccessMsg("收件人不存在！");
        }
        if (StrUtil.isEmpty(user.getEmail())) {
            return CommonResp.buildSuccessMsg("收件人邮箱不存在！");
        }
        try {
            // 执行一次拿一个令牌
            if (!rateLimiter.tryAcquire(1)) {
                return CommonResp.buildSuccessMsg("请求过于频繁，拒绝服务!");
            }
            MailUtil.send(mailAccount, user.getEmail(), request.getTitle(), request.getDetails(), true);
        } catch (Exception e) {
            return CommonResp.buildSuccessMsg("邮件发送失败！");
        }

        return CommonResp.buildSuccessMsg("邮件发送成功！");
    }

}
